/**
 * CustomComponentsDao.java
 *
 * Copyright (c) 2009 viorelt All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of viorelt .
 **/
package ro.prjmanager.dao;

import org.hibernate.Query;
import org.hibernate.SQLQuery;
import ro.prjmanager.core.dao.GenericDAO;
import ro.prjmanager.core.list.ListSqlParser;
import ro.prjmanager.core.list.SQL;
import ro.prjmanager.model.CustomComponents;
import ro.prjmanager.model.Groups;
import ro.prjmanager.model.Projects;

import java.util.List;

@SuppressWarnings({"unchecked"})
public class CustomComponentsDao extends GenericDAO<CustomComponents, Integer> {
    @SuppressWarnings({"unchecked"})
    public List<CustomComponents> list(Groups groups) {
        String sql = "SELECT * FROM CUSTOM_COMPONENTS WHERE FK_GROUP=" + groups.getId();
        SQLQuery sqlQuery = getSession().createSQLQuery(sql);
        return sqlQuery.addEntity(getPersistentClass()).list();

    }


    public CustomComponents findByIds(Integer idModel, Integer idGenericComponent, Integer idDetaliuComp) {
        StringBuilder sql = new StringBuilder("select c from ").append(getPersistentClass().getName()).append(" as c");
        sql.append(" join c.fkGroups as d");
        sql.append(" where d.fkProject.id=").append(((Projects)getUserSession().getProject()).getId());
        sql.append(" and c.fkModel.id=").append(idModel);
        sql.append(" and c.fkComponents.id=").append(idGenericComponent);
        sql.append(" and c.componentDetails.id=").append(idDetaliuComp);
        Query sqlQuery = getSession().createQuery(sql.toString());
        List<CustomComponents> comps=sqlQuery.list();
        if(comps!=null&&!comps.isEmpty())
            return comps.get(0);
        return null;
    }

    @Override

    public List<CustomComponents> listPagFilter(int startPage, int resPerPage, String sqlFilter) {
        StringBuilder sql =
                new StringBuilder("select c from ").append(getPersistentClass().getName()).append(" as c")
                        .append(" join c.fkGroups as d");


        SQL sqlFilterParsed = ListSqlParser.parseSqlListParameter(sqlFilter);
        sql.append(" ").append(sqlFilterParsed.getBeforeWhereParent());
        sql.append(" where d.fkProject.id=").append(((Projects)getUserSession().getProject()).getId());
        sql.append(" ").append(sqlFilterParsed.getAfterWhereParent().replace("where", "and"));

        Query sqlQuery = getSession().createQuery(sql.toString());
        sqlQuery.setMaxResults(resPerPage);
        sqlQuery.setFirstResult(startPage);
        return sqlQuery.list();
    }
}
